<template>
  <!-- 页面容器 -->
  <div class="app-container out-div-global">
<!--    <div class="out-div-global"></div>-->
    <div class="inner-div-normal">
      <!-- 查询条件表单 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <!-- 编码查询条件 -->
        <el-form-item label="编码" prop="administrativeCode">
          <el-input
              v-model="queryParams.administrativeCode"
              placeholder="请输入编码"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- 名称查询条件 -->
        <el-form-item label="名称" prop="administrativeName">
          <el-input
              v-model="queryParams.administrativeName"
              placeholder="请输入名称"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" plain icon="Search" @click="handleImport">导入</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮行 -->
      <el-row :gutter="10" class="mb8">
        <!-- 新增按钮 -->
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['system:administrative:add']"
          >新增</el-button>
        </el-col>
        <!-- 展开/折叠按钮 -->
        <el-col :span="1.5">
          <el-button
              type="info"
              plain
              icon="Sort"
              @click="toggleExpandAll"
          >折叠</el-button>
        </el-col>
        <!-- 右侧工具栏 -->
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <div class="inner-div-auto">
    <!-- 行政区表格 -->
      <!-- 修改后 -->
      <el-table
          v-if="refreshTable"
          v-loading="loading"
          :data="administrativeList"
          row-key="administrativeId"
          height="100%"
          lazy
          :load="loadChildren"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
      <!-- 显示顺序列 -->
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <!-- 编码列 -->
      <el-table-column label="编码" align="center" prop="administrativeCode" />
      <!-- 名称列 -->
      <el-table-column label="名称" align="center" prop="administrativeName" />
      <!-- 名称列 -->
      <el-table-column label="图层路径" align="center" prop="path" />

      <!-- 负责人列 -->
      <el-table-column label="负责人" align="center" prop="leader" />
      <!-- 联系电话列 -->
      <el-table-column label="联系电话" align="center" prop="phone" />
      <!-- 状态列 -->
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:administrative:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:administrative:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:administrative:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <!-- 添加或修改行政区对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="administrativeRef" :model="form" :rules="rules" label-width="120px">
        <!-- 父级选择 -->
          <el-form-item label="请选择父级" prop="parentId">
            <el-tree-select
                v-model="form.parentCode"
                :data="administrativeOptions"
                :props="{ value: 'administrativeCode', label: 'administrativeName', children: 'children' }"
                value-key="administrativeId"
                placeholder="请选择父级"
                check-strictly
                lazy
                :load="loadSelectTree"
            />
        </el-form-item>
        <!-- 编码输入 -->
        <el-form-item label="级别" prop="administrativeLevel">
          <el-select v-model="form.administrativeLevel" placeholder="请选择级别">
            <el-option label="省" value="1" />
            <el-option label="市" value="2" />
            <el-option label="区" value="3" />
          </el-select>
        </el-form-item>
        <!-- 编码输入 -->
        <el-form-item label="编码" prop="administrativeCode">
          <el-input v-model="form.administrativeCode" placeholder="请输入编码" />
        </el-form-item>
        <!-- 名称输入 -->
        <el-form-item label="名称" prop="administrativeName">
          <el-input v-model="form.administrativeName" placeholder="请输入名称" />
        </el-form-item>
        <!-- 图层路径 -->
        <el-form-item label="图层路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入名称" />
        </el-form-item>
        <!-- 显示顺序输入 -->
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
        <!-- 负责人输入 -->
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人" />
        </el-form-item>
        <!-- 联系电话输入 -->
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <!-- 状态选择 -->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 在现有对话框之后添加导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :auto-upload="false"
          :on-exceed="handleExceed"
          :on-change="handleFileChange"
          :file-list="fileList"
      >
        <el-button type="primary">选择文件</el-button>
        <!-- 显示已选择的文件名 -->
        <div v-if="fileList.length > 0" class="file-name">
          已选择: {{ fileList[0].name }}
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" class="link-type" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Administrative">
// 导入行政区相关API接口
import { importAdministrative, exportTemplate,listAdministrative, getAdministrative, delAdministrative, addAdministrative, updateAdministrative } from "@/api/system/administrative"

// 获取当前组件实例
const { proxy } = getCurrentInstance()
// 加载系统状态字典(sys_normal_disable表示正常/停用状态)
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")
// 存储行政区列表数据
const administrativeList = ref([])
// 存储行政区下拉树选项数据
const administrativeOptions = ref([])
// 控制对话框显示状态
const open = ref(false)
// 控制表格加载状态
const loading = ref(true)
// 控制搜索栏显示状态
const showSearch = ref(true)
// 存储对话框标题
const title = ref("")
// 控制树形表格是否默认展开所有节点
const isExpandAll = ref(true)
// 控制表格刷新状态
const refreshTable = ref(true)

// 导入相关数据
const upload = reactive({
  // 导入对话框标题
  title: "",
  // 是否显示导入对话框
  open: false,
  // 是否正在上传
  isUploading: false
})
// 文件列表
const fileList = ref([])
// 上传组件引用
const uploadRef = ref(null)
// 响应式数据对象
const data = reactive({
  // 表单数据模型
  form: {},
  // 查询参数
  queryParams: {
    parentCode: null,
    administrativeCode:null,
    ancestors: null,
    administrativeName: null,
    orderNum: null,
    leader: null,
    phone: null,
  },
  // 表单验证规则
  rules: {
    parentCode: [{ required: true, message: "上级行政单位不能为空", trigger: "blur" }],
    administrativeCode: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    administrativeName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    administrativeLevel: [{ required: true, message: "级别不能为空", trigger: "blur" }],
  },
})
//判断查询参数是否为空
function hasQueryParams(queryParams) {
    if(queryParams.value.administrativeCode != null && queryParams.value.administrativeCode != ""){
      return true;
    }
  if(queryParams.value.administrativeName != null && queryParams.value.administrativeName != ""){
    return true;
  }
  return false;
}
// 解构响应式数据以便在模板中使用
const { queryParams, form, rules } = toRefs(data)

/** 查询行政区列表 */
function getList() {
  // 设置加载状态为true
  debugger
  loading.value = true
  debugger
  console.info("🚀 ~ file:index method:getList line:300 -----",queryParams )
  console.info("🚀 ~ file:index method:getList line:300 -----",queryParams.value )
  // 调用API获取行政区列表数据
if(!hasQueryParams(queryParams)){
  queryParams.value.parentCode = "-1"
}else {
  queryParams.value.parentCode = null
}
  listAdministrative(queryParams.value).then(response => {
    // 使用handleTree方法将扁平数据转换为树形结构
    administrativeList.value = response.data
    // 设置加载状态为false
    loading.value = false
  })
}

/** 查询行政区下拉树结构 */
function getTreeselect() {
  // 调用API获取行政区数据
  listAdministrative().then(response => {
    // 清空选项数组
    administrativeOptions.value = []
    // 创建顶级节点数据
    const data = { administrativeId: 0, administrativeName: '中华人民共和国',administrativeCode: '-1', children: [] }
    // 使用handleTree方法将数据转换为树形结构
    data.children = proxy.handleTree(response.data, "administrativeCode", "parentCode")
    debugger
    // 将顶级节点添加到选项数组中
    administrativeOptions.value.push(data.children[0])
  })
}

// 取消按钮处理函数
function cancel() {
  // 关闭对话框
  open.value = false
  // 重置表单
  reset()
}

/** 导入按钮操作 */
function handleImport() {
  // 重置文件列表
  fileList.value = []
  // 设置上传参数
  upload.title = "行政区划数据导入"
  upload.open = true
  upload.isUploading = false
}
/** 处理文件超出限制 */
function handleExceed() {
  proxy.$modal.msgError("只能上传一个文件")
}

/** 文件选择变化时的处理 */
function handleFileChange(file, listFile) {
  console.log(fileList)
  fileList.value = listFile
}

/**
* 懒加载子级数据
* @param tree 当前行数据
* @param treeNode 树节点对象
* @param resolve 解析函数
*/
function loadChildren(tree, treeNode, resolve) {
  // 使用当前行的 administrativeCode 作为 parentCode 查询子级数据
  listAdministrative({ parentCode: tree.administrativeCode }).then(response => {
    // 将返回的数据转换为树形结构并解析
    const children = proxy.handleTree(response.data, "administrativeCode", "parentCode");
    resolve(children);
  });
}
/** 提交上传文件 */
function submitFileForm() {
  // 检查是否有选择文件
  debugger
  if (fileList.value.length === 0) {
    proxy.$modal.msgError("请选择上传文件")
    return
  }

  // 设置上传状态
  upload.isUploading = true

  // 创建表单数据
  const formData = new FormData()
  formData.append("file", fileList.value[0].raw)
  // 确保设置正确的请求头
  const config = {
    headers: {
      "Content-Type": "multipart/form-data"
    }
  }
  // 调用导入API
  importAdministrative(formData,config).then(response => {
    // 关闭导入对话框
    upload.open = false
    // 显示导入结果
    proxy.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg + "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
    )
    // 刷新列表
    getList()
  }).finally(() => {
    // 恢复上传状态
    upload.isUploading = false
  })
}
// 表单重置处理函数
function reset() {
  // 重置表单数据
  form.value = {
    administrativeId: null,
    parentId: null,
    ancestors: null,
    administrativeName: null,
    orderNum: null,
    leader: null,
    phone: null,
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  // 重置表单验证状态
  proxy.resetForm("administrativeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  // 执行查询操作
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  // 重置查询表单
  proxy.resetForm("queryRef")
  // 执行查询操作
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  // 重置表单
  reset()
  // 获取下拉树数据
  getTreeselect()
  // 设置父级ID，默认为顶级节点(0)
  if (row != null && row.administrativeId) {
    form.value.parentId = row.administrativeId
  } else {
    form.value.parentId = 0
  }
  // 设置默认状态为启用(0)
  form.value.status="0";
  // 打开对话框
  open.value = true
  // 设置对话框标题
  title.value = "添加行政区"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  // 刷新表格状态设为false
  refreshTable.value = false
  // 切换展开状态
  isExpandAll.value = !isExpandAll.value
  // 在下一个DOM更新周期后重新设置刷新状态为true
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  // 异步重置表单
  await reset()
  // 异步获取下拉树数据
  await getTreeselect()
  // 设置父级ID
  if (row != null) {
    form.value.parentId = row.parentId
  }
  // 调用API获取行政区详情数据
  getAdministrative(row.administrativeId).then(response => {
    // 设置表单数据
    form.value = response.data
    // 打开对话框
    open.value = true
    // 设置对话框标题
    title.value = "修改行政区"
  })
}

/** 提交按钮 */
function submitForm() {
  // 表单验证
  proxy.$refs["administrativeRef"].validate(valid => {
    // 验证通过时执行提交操作
    if (valid) {
      // 判断是更新还是新增操作
      if (form.value.administrativeId != null) {
        // 更新行政区信息
        updateAdministrative(form.value).then(response => {
          // 显示成功消息
          proxy.$modal.msgSuccess("修改成功")
          // 关闭对话框
          open.value = false
          // 刷新列表数据
          getList()
        })
      } else {
        // 新增行政区信息
        addAdministrative(form.value).then(response => {
          // 显示成功消息
          proxy.$modal.msgSuccess("新增成功")
          // 关闭对话框
          open.value = false
          // 刷新列表数据
          getList()
        })
      }
    }
  })
}
/**
 * 懒加载树形选择器数据
 * @param node 当前节点
 * @param resolve 解析函数
 */
function loadSelectTree(node, resolve) {
  const { level, data } = node;

  // 根节点加载
  if (level === 0) {
    const rootData = [{
      administrativeId: 0,
      administrativeCode: '-1',
      administrativeName: '顶级节点',
      children: null
    }];
    resolve(rootData);
    return;
  }

  // 加载子节点数据
  const parentCode = data.administrativeCode;
  listAdministrative({ parentCode: parentCode }).then(response => {
    const children = response.data || [];
    resolve(children);
  }).catch(() => {
    resolve([]);
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  // 确认删除操作
  proxy.$modal.confirm('是否确认删除行政区编号为"' + row.administrativeId + '"的数据项？').then(function() {
    // 调用API删除行政区
    return delAdministrative(row.administrativeId)
  }).then(() => {
    // 刷新列表数据
    getList()
    // 显示删除成功消息
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 初始化加载数据
getList()
</script>
